package vikaa.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vikaa.wowo.widget.PullToRefreshListView;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.WeiboParameters;
import com.weibo.sdk.android.api.FriendshipsAPI;
import com.weibo.sdk.android.net.RequestListener;

import vikaa.adapter.WeiboFriendListAdapter;
import vikaa.bean.WeiboFriend;
import vikaa.timelinepackage.Timeline;
import vikaa.timelinepackage.TimelineImportWeibo;
import vikaa.timelinepackage.TimelineImport;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.Logger;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.InvitorSqlStoragePrivate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class WeiboFriendChoose extends Activity implements RequestListener{
	private PullToRefreshListView lv;
	private View lv_footer;
	private LinearLayout footer;
	private ProgressBar lv_foot_pb;
	private TextView lv_foot_more;
	private int visibleLastIndex = 0;  
    private int visibleItemCount;       
    private int count=0;
	private boolean ran = true;
	
	private LinearLayout backBtn;
	private EditText searchEdt;
	private WeiboFriendListAdapter mAdapter;
	private ArrayList<WeiboFriend> wbfList = new ArrayList<WeiboFriend>() ;
	public ArrayList<WeiboFriend> mList = new ArrayList<WeiboFriend>();
	private int next_cursor = 0;
	public static boolean setflag = false;
	public static boolean callflag = false;
	public static boolean inviteflag = false;
	private ImageView submitBtn;
	private InputMethodManager imm;
	public static WeiboFriendChoose wc;
	private ImageView deleteBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_weibo_friend_choose);
		wc = this;
		initdata();
		initview();
		imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(callflag || inviteflag){
			callflag = false;
			inviteflag = false;
			InvitorSqlStoragePrivate.refreshWeibofd(WeiboFriendChoose.this);
			InvitorSqlStoragePrivate.dropchoosed(WeiboFriendChoose.this);
		}
	}
	private void initListView()
    {
        mAdapter = new WeiboFriendListAdapter(this, mList);        
        lv_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
        lv_foot_pb = (ProgressBar)lv_footer.findViewById(R.id.listview_foot_progress);
        //lv_foot_pb.setVisibility(View.INVISIBLE);
        footer = (LinearLayout)lv_footer.findViewById(R.id.footer);
        lv_foot_more = (TextView)lv_footer.findViewById(R.id.listview_foot_more);
        //lv_foot_more.setText(R.string.load_more);
        lv = (PullToRefreshListView)findViewById(R.id.frame_listview);
        lv.addFooterView(lv_footer);//添加底部视图  必须在setAdapter前
        lv.setAdapter(mAdapter); 
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long lid) {
        		if(position == 0 || view == lv_footer) return;
        		imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
        		if(!setflag){
        			WeiboFriend wf = new WeiboFriend();
                	String id = mList.get(position-1).getId();
                	String name = mList.get(position-1).getName();
                    wf.setId(id);
                    wf.setName(name);
                    wf.setPhone("no");
                    InvitorSqlStoragePrivate.updateWeibofdSql(id, !(mList.get(position-1).isSelected()),getApplicationContext());
                    if(!(mList.get(position-1).isSelected()) == true){
                    	InvitorSqlStoragePrivate.saveChoosedinSql(wf, getApplicationContext());
                    }else{
                    	InvitorSqlStoragePrivate.delectChoosedinSql(wf,getApplicationContext());
                    }
        	        mAdapter.changeState(position-1,view);
        		}
        		else{//timelinesetting call
        			Intent it = new Intent(WeiboFriendChoose.this,TimelineImportWeibo.class);
        			it.putExtra("space_id", TimelineImport.space_id);
        			it.putExtra("role", TimelineImport.role);
        			it.putExtra("weibo_uid", mList.get(position-1).getId());
        			startActivity(it);
        			finish();
        		}
        	}        	
		});
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lv.onScrollStateChanged(view, scrollState);
				//数据为空--不用继续下面代码了
				if(mList.size() == 0) return;
				
				lv_footer.setVisibility(View.VISIBLE);
				int itemsLastIndex = mList.size()-1; 
		        int lastIndex = itemsLastIndex ;  
		        
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  
		                && visibleLastIndex == lastIndex  && ran & next_cursor != 0) {  
					lv_footer.setVisibility(View.VISIBLE);
					lv_foot_pb.setVisibility(View.VISIBLE);
					lv_foot_more.setText(R.string.load_ing);
					wbfList.clear();
					new GetFriendThread(6).start();
					ran = false;
		        } else if (next_cursor == 0){
		        	lv.removeFooterView(lv_footer);
		        }
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				lv.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
		        visibleLastIndex = firstVisibleItem-1 + visibleItemCount -2; 
		        count = totalItemCount;
			}
		});
        lv.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            public void onRefresh() {
            	//new GetFriendThread("count", next_cursor ,5).start();
            	lv.postDelayed(new Runnable() {
					public void run() {
						lv.onRefreshComplete();
					}
				}, 2000);
            	
            }
        });					
    }
	public void initview(){
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		initListView();
		//DialogService.showProgressDialog(WeiboFriendChoose.this, getString(R.string.get_friend));
		deleteBtn = (ImageView)findViewById(R.id.delete);
        searchEdt = (EditText)findViewById(R.id.searchEdt);
        searchEdt.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == 66 && event.getAction() == KeyEvent.ACTION_DOWN){
					mList.clear();
					mAdapter.notifyDataSetChanged();
					lv_footer.setVisibility(View.GONE);
					lv.state = lv.REFRESHING;
					lv.changeHeaderViewByState();  
					DialogService.hideSoftKeypad(WeiboFriendChoose.this);
					new SearchFriendThread(searchEdt.getText().toString()).start();
				}
				return false;
			}
		});
        searchEdt.addTextChangedListener(new TextWatcher() {
        	 private CharSequence temp;
             private int editStart ;
             private int editEnd ;
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				temp = s;
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			public void afterTextChanged(Editable s) {
					editStart = searchEdt.getSelectionStart();
		            editEnd = searchEdt.getSelectionEnd();
		            if(temp.length() == 0){
		            	mList.clear();
		            	ran = true;
						mAdapter.notifyDataSetChanged();
						initdata();
						deleteBtn.setVisibility(View.INVISIBLE);
		            }else{
		            	deleteBtn.setVisibility(View.VISIBLE);
		            }
			}
		});
        
        deleteBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				searchEdt.setText("");
			}
		});
        if(callflag || inviteflag){
        	submitBtn = (ImageView)findViewById(R.id.submitBtn);
        	submitBtn.setVisibility(View.VISIBLE);
        	submitBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
					wbfList.clear();
					wbfList = InvitorSqlStoragePrivate.getChoosedinSql(getApplicationContext());
					switch(wbfList.size()){
					case 0:
						new AlertDialog.Builder(WeiboFriendChoose.this).setTitle("提示").setMessage("请选择好友进行召唤")
						.setPositiveButton("返回", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
							}
						}).show();
						break;
						default:
							//DialogService.showProgressDialog(WeiboFriendChoose.this, getString(R.string.inviting));
							if(callflag){
								String members = convert2Friends();
								new CallThread(Timeline.space_id, members).start();
							}
							if(inviteflag){
								WowoCreate4.inviteflag = true;
								Intent i = new Intent(WeiboFriendChoose.this,WowoCreate4.class);
								i.putExtra("name", Timeline.space_name);
								i.putExtra("state", Timeline.state);
								startActivity(i);
							}
							break;
					}
				}
			});
        }else{
        	submitBtn = (ImageView)findViewById(R.id.submitBtn);
        	submitBtn.setVisibility(View.INVISIBLE);
        }
	}
	public void initdata(){
	    if ((wbfList=InvitorSqlStoragePrivate.getWeibofdFromSql(getApplicationContext())).size()>0){ 
			next_cursor = 50;
			Message msg = mhandler.obtainMessage(1);
			msg.obj = wbfList;
			msg.sendToTarget();
	    }
	    else
	    	new GetFriendThread(1).start();
	}
	public String convert2Friends(){
		String members = "[";
		for(int i=0;i<wbfList.size()-1;i++){
				members += wbfList.get(i).toFriends() +","; 
			}
		members += wbfList.get(wbfList.size()-1).toFriends() +"]"; 
		return members;
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case 0://search
				//DialogService.closeProgressDialog();
				//header.setVisibility(View.GONE);
				lv.state = lv.DONE;
				lv.changeHeaderViewByState();  
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.clear();
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			case 1:
				//DialogService.closeProgressDialog();
				//header.setVisibility(View.GONE);
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			case 2:
				//DialogService.closeProgressDialog();
				//header.setVisibility(View.GONE);
				finish();
				break;
			case 3:
				//DialogService.closeProgressDialog();
				//header.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(WeiboFriendChoose.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(WeiboFriendChoose.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				//DialogService.closeProgressDialog();
				//header.setVisibility(View.GONE);
				Toast.makeText(WeiboFriendChoose.this, /*R.string.network_crash*/(String)msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case 5://pull refresh
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				lv.onRefreshComplete(getString(R.string.pull_to_refresh_update) + "22");
				lv.setSelection(0);
				break;
			case 6://load more
				ran = true;
				lv_foot_more.setText(R.string.load_more);
				lv_foot_pb.setVisibility(View.INVISIBLE);
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
				
			}
		}
	};
	
	public void getFriends(final int m, int cursor) {
		//Logger.i(AuthoSharePreference.getExpires(WeiboFriendChoose.this));
		FriendshipsAPI friendApi = new FriendshipsAPI(new Oauth2AccessToken(AuthoSharePreference.getToken(WeiboFriendChoose.this), AuthoSharePreference.getExpires(WeiboFriendChoose.this)));
		friendApi.friends(Long.valueOf(AuthoSharePreference.getUid(WeiboFriendChoose.this)), 50, cursor, true , new RequestListener() {
			@Override
			public void onIOException(IOException e) {
				
			}
			
			@Override
			public void onError(WeiboException e) {
				
			}
			
			@Override
			public void onComplete(String response) {
				//Logger.i(response);
				try{
					JSONObject list = new JSONObject(response);
					//Logger.i(list.toString());
					JSONArray friendlist =  list.getJSONArray("users");
					for(int i=0;i<friendlist.length();i++){
						WeiboFriend wf = new WeiboFriend();
						wf.setName(friendlist.getJSONObject(i).getString("name"));
						wf.setId(String.valueOf(friendlist.getJSONObject(i).getLong("id")));
						wf.setSelected(false);
						wf.setPhone("");
						wbfList.add(wf);
					}
					InvitorSqlStoragePrivate.SaveWeibofdInSql(wbfList,getApplicationContext());
					next_cursor = Integer.valueOf(list.getString("next_cursor"));
					Message msg = mhandler.obtainMessage(m);
					msg.obj = wbfList;
					msg.sendToTarget();
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}
	class GetFriendThread extends Thread{
		private boolean isrun = true;
		private int m;
		public GetFriendThread(int m) {
			super();
			this.m = m;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				WeiboFriendChoose.this.getFriends(m,next_cursor);
			}
		}
	}
	class SearchFriendThread extends Thread{
		private boolean isrun = true;
		private String value;
		public SearchFriendThread(String value) {
			super();
			this.value = value;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					wbfList.clear();
					Map<String, String> map = new HashMap<String, String>();
					map.put("q", value);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/searchatuser", map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						JSONArray friendlist =  jsonObj.getJSONArray("info");
						for(int i=0;i<friendlist.length();i++){
							WeiboFriend wf = new WeiboFriend();
							wf.setName(friendlist.getJSONObject(i).getString("nickname"));
							wf.setId(String.valueOf(friendlist.getJSONObject(i).getLong("uid")));
							wf.setSelected(false);
							wf.setPhone("");
							wbfList.add(wf);
						}
						Message msg = mhandler.obtainMessage(0);
						msg.obj = wbfList;
						msg.sendToTarget();
					}else if(result.equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		DialogService.hideSoftKeypad(WeiboFriendChoose.this);
		return super.dispatchTouchEvent(ev);
		
	}
	
	
	class WowoInviteThread extends Thread{
    	boolean isrun = true;
    	private String space_id;
    	private String members;
    	private String message;
    	public WowoInviteThread(String space_id, String members, String message) {
			super();
			this.space_id = space_id;
			this.members = members;
			this.message = message;
		}
		@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("space_id", space_id);
    			map.put("members", members);
    			map.put("message", message);
    			String url = HttpUtil.BASE_URL + "space/invite";
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						Message msg = mhandler.obtainMessage(2);
						mhandler.sendMessage(msg);
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.obj = jsonObj.getString("msg");
						mhandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
	class CallThread extends Thread{
    	boolean isrun = true;
    	private String space_id;
    	private String friends;
    	public CallThread(String space_id, String members) {
			super();
			this.space_id = space_id;
			this.friends = members;
		}
		@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("space_id", space_id);
    			map.put("friends", friends);
    			String url = HttpUtil.BASE_URL + "space/callfriends";
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						Message msg = mhandler.obtainMessage(2);
						mhandler.sendMessage(msg);
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.obj = jsonObj.getString("msg");
						mhandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }

	@Override
	public void onComplete(String response) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onError(WeiboException e) {
		// TODO Auto-generated method stub
		
	}
}
